const express = require('express');
const uuid = require('node-uuid');
const { Message,MessageList } = require('../utils/message');
const employeeModel = require('../models/employee');
const { query } = require('express');

const router = express.Router();

router.post('/',(req,res,next)=>{
  const {name,sex,age,birthday,cid,phone,address,baseWage,type}=req.body;
  let {joinTime=new Date()}=req.body;
  const id=uuid.v1();
  const employee=new employeeModel({id,name,sex,age,birthday,cid,phone,address,baseWage,joinTime,type});
  employee.save().then(data=>{
    if(data){
      res.json(Message(200,'添加成功！'));
    }
  });
});

router.delete('/',(req,res,next)=>{
  const {id}=req.query;
  if(id){
    employeeModel.deleteOne({id}).then(data=>{
      if(data.deletedCount!==0){
        res.json(Message(200,'删除成功！'))
      }else{
        res.json(Message(400,'删除失败'))
      }
    })
  }else{
    res.json(Message(400,'缺少参数id'))
  }
})

router.put('/',(req,res,next)=>{
  const {id}=req.query;
  const {age,sex,birthday,cid,phone,type,address}=req.body;
  if(id){
    employeeModel.updateOne({id},{age,sex,birthday,cid,phone,type,address}).then(data=>{
      console.log(data)
      if(data.acknowledged&&data.modifiedCount!==0){
        res.json(Message(200,'修改成功！'));
      }else{
        res.json(Message(400,'修改失败！'));
      }
    })
  }else{
    res.json(Message(400,'缺少参数id'));
  }
})

router.get('/',(req,res,next)=>{
  let {id,name,type,page,pageSize}=req.query;
  let regexp=new RegExp(name,'i');
  const queryObj={};
  if(id) {
    queryObj.id=id;
    employeeModel.findOne({id}).then(data=>{
      if(data){
        res.json(Message(200,'',data))
      }
    })
    return
  }
  if(name) queryObj.$or=[{name:{$regex:regexp}}];
  if(type) queryObj.type=type;
  if(page&&pageSize){
    employeeModel.find(queryObj).count((err,count)=>{
      employeeModel.find(queryObj)
        .limit(pageSize)
        .skip((page-1)*pageSize)
        .then(data=>{
          res.json(MessageList(200,'',data,page,pageSize,count));
        })
    })
  }else{
    employeeModel.find(queryObj).count((err,count)=>{
      employeeModel.find(queryObj).then(data=>{
          res.json(MessageList(200,'',data,0,0,count));
        })
    })
  }
  
  // if(name){//模糊查询列表
  //   employeeModel.find({$or: [{name:{$regex:regexp}}]}).count((err,count)=>{
  //     employeeModel.find({$or: [{name:{$regex:regexp}}]})
  //       .limit(pageSize)
  //       .skip((page-1)*pageSize)
  //       .then(data=>{
  //         res.json(MessageList(200,'',data,page,pageSize,count));
  //       })
  //   })
  // }else{//全部查询列表
  //   employeeModel.countDocuments((err,count)=>{
  //     employeeModel.find().limit(pageSize).skip((page-1)*pageSize).then(data=>{
  //       res.json(MessageList(200,'',data,page,pageSize,count));
  //     })
  //   })
  // }
})
module.exports = router